<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>六宫银两查询-终极版</title>
    <style>
        body {
            background: #f8f0e0;
            font-family: "楷体", serif;
            padding: 15px;
            color: #5c3317;
        }
        .container {
            max-width: 100%;
            background: rgba(255, 248, 220, 0.9);
            border: 1px solid #c0a080;
            border-radius: 8px;
            padding: 15px;
            margin: 0 auto;
        }
        select, input, button {
            width: 100%;
            padding: 12px;
            margin: 8px 0;
            font-size: 16px;
            font-family: "楷体";
            border: 1px solid #8B4513;
            border-radius: 6px;
            box-sizing: border-box;
        }
        button {
            background: #8B4513;
            color: white;
            font-weight: bold;
        }
        .result {
            margin-top: 15px;
            padding: 12px;
            background: rgba(255, 248, 220, 0.7);
            border: 1px dashed #8B4513;
            border-radius: 6px;
        }
        .error {
            color: red;
            border-left: 3px solid red;
            padding-left: 10px;
        }
        .loader {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #8B4513;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 1s linear infinite;
            margin: 10px auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 style="text-align:center;color:#8B0000;margin-top:0;">🏯 六宫银两查询</h2>
        
        <select id="sheetSelect">
            <option value="妃">妃嫔账簿</option>
            <option value="皇嗣">皇嗣账簿</option>
            <option value="宗">宗亲账簿</option>
            <option value="宫人">宫人账簿</option>
        </select>
        
        <input type="text" id="nameInput" placeholder="输入姓名">
        <button onclick="searchData()">查 询</button>
        
        <div id="result" class="result" style="display:none;"></div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

    <script>
        // 定义你的Excel文件链接
        const EXCEL_URL = 'https://gitee.com/lyq0041699547/funyunyue-search/raw/master/content_1754887704145.xlsx';
        
        // 全局变量来缓存数据，避免重复下载
        let workbookCache = null;

        /**
         * 显示错误信息
         * @param {string} message - 要显示的错误消息
         */
        function showError(message) {
            const resultDiv = document.getElementById('result');
            resultDiv.style.display = 'block';
            resultDiv.innerHTML = `<div class="error">${message}</div>`;
        }

        /**
         * 主查询函数
         */
        async function searchData() {
            const name = document.getElementById('nameInput').value.trim();
            const sheetName = document.getElementById('sheetSelect').value;
            const resultDiv = document.getElementById('result');
            
            resultDiv.innerHTML = '<div class="loader"></div><p>尚宫局核验中...</p>';
            resultDiv.style.display = 'block';
            
            if (!name) {
                showError('请先输入姓名！');
                return;
            }

            try {
                const workbook = await getWorkbook();

                if (!workbook.SheetNames.includes(sheetName)) {
                    throw new Error(`未找到「${sheetName}」分册`);
                }
                const worksheet = workbook.Sheets[sheetName];

                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                const foundRow = jsonData.find(row => row[0] && row[0].includes(name));

                if (foundRow) {
                    resultDiv.innerHTML = `
                        <h3 style="color:#8B0000">${foundRow[0]}</h3>
                        <p>所在册籍：<b>${sheetName}</b></p>
                        <p>天祐元年：<b>${foundRow[1] || '0'}</b> 两</p>
                    `;
                } else {
                    showError(`未能找到「${name}」的记录，请检查姓名是否输入正确。`);
                }

            } catch (error) {
                showError(`御前尚宫急报：${error.message}`);
            }
        }

        /**
         * 获取并解析Excel文件，使用缓存机制
         * @returns {Promise<Object>} Excel工作簿对象
         */
        async function getWorkbook() {
            if (workbookCache) {
                document.getElementById('result').innerHTML += '<p>已使用缓存数据。</p>';
                return workbookCache;
            }

            document.getElementById('result').innerHTML += '<p>正在连接尚宫局总册...</p>';
            
            const response = await fetch(EXCEL_URL);
            if (!response.ok) {
                throw new Error(`无法连接尚宫局总册，状态码: ${response.status}`);
            }
            
            document.getElementById('result').innerHTML += '<p>正在解封凤印文书...</p>';
            const arrayBuffer = await response.arrayBuffer();
            const data = new Uint8Array(arrayBuffer);
            
            document.getElementById('result').innerHTML += '<p>正在核对各宫分册...</p>';
            const workbook = XLSX.read(data, { type: 'array' });
            
            workbookCache = workbook;
            return workbook;
        }
    </script>
</body>
</html>